package com.maddox.relax.permission

import android.content.pm.PackageManager
import androidx.fragment.app.Fragment

//减少函数的复杂性,给指定函数设置别名
typealias PermissionOnCallback = (Boolean,List<String>)->Unit
/**
 * 用于申请权限的透明Fragment
 */
class LucencyFragment : Fragment() {

    //声明一个函数回调,参数分别表示是否全部授权和未授权的权限名称
    private var callBack: PermissionOnCallback? = null

    //请求权限
    fun requestNow(cb: PermissionOnCallback, vararg permissions: String) {
        callBack = cb
        requestPermissions(permissions, 1)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == 1) {
            val deniedList = ArrayList<String>()
            //遍历权限列表,记录未授权的权限结果
            for ((index, result) in grantResults.withIndex()) {
               if (result!=PackageManager.PERMISSION_GRANTED){
                   deniedList.add(permissions[index])
               }
            }
            val allGranted = deniedList.isEmpty()
            //通过函数回调结果
            callBack?.let {
                it(allGranted,deniedList)
            }
        }


    }


}